package com.example.service.impl;

import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.context.BaseContext;
import com.example.dto.FilesPageDTO;
import com.example.entity.Homework;
import com.example.entity.Login;
import com.example.entity.Mapfile;
import com.example.entity.Modelfiles;
import com.example.mapper.HomeworkMapper;
import com.example.mapper.LoginMapper;
import com.example.mapper.MapfileMapper;
import com.example.result.PageResult;
import com.example.service.IMapfileService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.utils.BaseException;
import com.example.utils.CommonControllers;
import com.example.vo.MapfilesVO;
import com.example.vo.ModelfilesVO;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 陈昌吉
 * @since 2024-04-16
 */
@Service
public class MapfileServiceImpl extends ServiceImpl<MapfileMapper, Mapfile> implements IMapfileService {
    @Autowired
    private MapfileMapper mapfileMapper;
    @Autowired
    private CommonControllers commonControllers;
    @Autowired
    private HomeworkMapper homeworkMapper;
    @Autowired
    private LoginMapper loginMapper;

    /**
     * 新增UV贴图文件
     * @param file
     * @param hid
     * @return
     */
    @Override
    public List<Mapfile> insertFile(MultipartFile file, Integer hid) {

        //判断作业上交时间是否截止
        Homework homework = homeworkMapper.selectById(hid);
        System.out.println(LocalDateTime.now().isBefore(homework.getEndtime()));
        if (LocalDateTime.now().isBefore(homework.getEndtime())==false){
            throw new BaseException("作业时间已结束，不能在提交",500);
        }

        String originalFilename = file.getOriginalFilename();//获取文件原始名称
        //String s = FileUtil.mainName(originalFilename);//获取文件前面名不含后缀
        //String s1 = FileUtil.extName(originalFilename);//获取文件后缀名

        //判断文件名是否重复
        QueryWrapper<Mapfile> mapfileQueryWrapper = new QueryWrapper<>();
        List<Mapfile> modelname =  mapfileMapper.selectList(mapfileQueryWrapper.eq("name", originalFilename));
        if(modelname.size()!=0){
            throw new BaseException("该文件已存在，不能重复上传",500);
        }

        String upload = String.valueOf(commonControllers.upload(file));//获取返回的url

        Mapfile build = Mapfile.builder()
                .url(upload)
                .hid(hid)
                .loginId(BaseContext.getCurrentId())
                .name(originalFilename)
                .uploadtime(LocalDateTime.now())
                .build();

        mapfileMapper.insert(build);

        //查询更新文件

        List<Mapfile> mapfiles = mapfileMapper.selectList(mapfileQueryWrapper.eq("login_id", BaseContext.getCurrentId()).eq("hid", hid));

        return mapfiles;
    }

    /**
     * 根据作业ID获取以提交VU贴图文件
     * @param hid
     * @return
     */
    @Override
    public List<Mapfile> select(Integer hid) {
        QueryWrapper<Mapfile> mapfileQueryWrapper = new QueryWrapper<>();
        List<Mapfile> mapfiles = mapfileMapper.selectList(mapfileQueryWrapper.eq("login_id", BaseContext.getCurrentId()).eq("hid", hid));

        return mapfiles;
    }

    /**
     * 删除UV贴图文件
     * @param mapfile
     */
    @Transactional
    @Override
    public void deleteById(Mapfile mapfile) {
        commonControllers.delete(mapfile.getUrl());
        mapfileMapper.deleteById(mapfile.getId());
    }

    /**
     * 获取审核文件相关接口
     * @param filesPageDTO
     * @return
     */
    @Override
    public PageResult selectAll(FilesPageDTO filesPageDTO) {
       // PageHelper.startPage(filesPageDTO.getPageNum(),filesPageDTO.getPageSize());
        Integer currentId = BaseContext.getCurrentId();
        Login login = loginMapper.selectByID(currentId);

       // PageHelper.startPage(filesPageDTO.getPageNum(),filesPageDTO.getPageSize());
        //判断当前角色0（老师）,1（助教）,2（学生）
        if (login.getRole().equals("0")){
            filesPageDTO.setSta("合格");
        }else if (login.getRole().equals("1")){
            filesPageDTO.setSta("待审核");
        }else{
            return null;
        }
        //开始分页查询
        PageHelper.startPage(filesPageDTO.getPageNum(), filesPageDTO.getPageSize());

        Page<MapfilesVO> page = mapfileMapper.selectAll(filesPageDTO.getHid(),filesPageDTO.getSta(),filesPageDTO.getState());

        long total = page.getTotal();
        List<MapfilesVO> records = page.getResult();

        return new PageResult(total, records);

//        Page<MapfilesVO> page = (Page<MapfilesVO>) mapfileMapper.selectAll(filesPageDTO.getHid(),filesPageDTO.getSta(),filesPageDTO.getState());
//        System.out.println(page);
//        long total = page.getTotal();
//        List<MapfilesVO> records = page.getResult();
//        return new PageResult(total, records);
    }

    /**
     * 修改UV贴图状态相关接口
     * @param mapfile
     * @return
     */
    @Override
    public void updateMapFiles(Mapfile mapfile) {
        mapfileMapper.updateMapFiles(mapfile);
    }
}
